package com.epfresh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.CartOrderExpandListAdapter;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.bean.Address;
import com.epfresh.bean.CartGood;
import com.epfresh.bean.CartGoods;
import com.epfresh.bean.CartList;
import com.epfresh.bean.*;
import com.epfresh.bean.CouponEntity;
import com.epfresh.bean.Feed;
import com.epfresh.bean.FeedRequest;
import com.epfresh.bean.MarketCart;
import com.epfresh.bean.PaymentModes;
import com.epfresh.bean.StoreGoodsPrice;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.MultiStateView;
import com.epfresh.views.dialog.*;
import com.epfresh.views.dialog.MerMsgDialog;
import com.epfresh.views.dialog.OrderFailDialog;
import com.epfresh.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CartOrderNewActivity extends BaseActivity {

    //freight运费字段

    private View vEmptyAddress;
    private View vAddress;
    private TextView tvTotal;
    private TextView tvTitle;
    private TextView tvAddressName;
    private TextView tvReduceFeeTitle;
    private TextView tvReduceFee;
    private TextView tvDetail;
    private TextView tvDiscountPrice;
    private TextView tvPursePrice;
    private TextView tvDiscount;
    private TextView tvPurse;
    private View vRight;
    private TextView tvFootTotal;
    private TextView tvFootOtherPrice;
    private TextView tvFootFirst;
    private TextView tvFootLast;
    private TextView tvPay_1;
    private TextView tvPay_2;
    private TextView tvBtn;
    private TextView tvTimeDetail;
    private View vTime;
    private CartOrderExpandListAdapter adapter;
    private List<MarketCart> groups = new ArrayList<>();

    private Address address;

    boolean isFeeError;

    boolean isPaymentFirst = true;
    boolean isOnlinePayment = true;

    CartList cartList;

    //preProduct != null 是预售商品
    private String preProduct;
    private Map<String, Object> preProductMap;
    private String marketId;

    private Map<String, CartGood> cartMap = new HashMap<>();

    private String storePriceStr = "";
    private double freight;

    //存储留言
    private Map<String, String> mapMsg = new HashMap<>();
    private RelativeLayout rl_price;
    private TextView tv_total_name;

    private String payType;
    private String deliveryType;
    private View tipOverScope;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_order);


        if (savedInstanceState != null) {
            getIntent().putExtra("preProduct", savedInstanceState.getString("preProduct"));
            getIntent().putExtra("marketId", savedInstanceState.getString("marketId"));
            getIntent().putExtra("storePrice", savedInstanceState.getString("storePrice"));
        }

        preProduct = getIntent().getStringExtra("preProduct");
        if (preProduct != null) {
            preProductMap = new Gson().fromJson(preProduct, new TypeToken<Map<String, Object>>() {
            }.getType());
            marketId = getIntent().getStringExtra("marketId");
//            storePriceStr = getIntent().getStringExtra("storePrice");
        } else {
            storePriceStr = getAllStores();
        }
        initView();


    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("preProduct", preProduct);
        outState.putString("marketId", marketId);
        outState.putString("storePrice", storePriceStr);
        super.onSaveInstanceState(outState);
    }

    boolean selfFlag;

    private void initView() {
        toolbarTitle.setText(R.string.ensure_order);
        ivBack.setVisibility(View.VISIBLE);

        righticon.setVisibility(View.VISIBLE);
        righticon.setImageResource(R.mipmap.refresh_fee);
        righticon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        righticon.setVisibility(View.GONE);
        righticon.setOnClickListener(this);
        tv_total_name = (TextView) findViewById(R.id.tv_total_name);
        tvTotal = (TextView) findViewById(R.id.tv_total);
        tvBtn = (TextView) findViewById(R.id.tv_btn);
        tvBtn.setOnClickListener(this);


        MultiStateView msView = (MultiStateView) findViewById(R.id.ms_view);
        ExpandableListView lv = (ExpandableListView) findViewById(R.id.lv);
        adapter = new CartOrderExpandListAdapter(this, lv, groups);

        adapter.setOnMerMsgListener(new CartOrderExpandListAdapter.OnMerMsgListener() {
            @Override
            public void onMerMsgListener(int groupPosition, int position, CartGood data) {
                if (data != null) {

                    requestFastMerTagList(data);
                }
            }
        });
        adapter.setOnRadioGroupListener(new CartOrderExpandListAdapter.OnRadioGroupListener() {
            @Override
            public void onRadioGroup(int groupPosition, int childPosition, int index) {

                if (index == 2) {//集单配送
                    deliveryType = "集单配送";
                    updateColumnView();
//                    requestAllFee();
                    selfFlag = false;
                    requestSigleFee(groups.get(groupPosition));
                    showPayWayViewChange();
                    reCountPrice();

                } else {//到店自提
                    deliveryType = "到店自提";
                    updateColumnView();
                    selfFlag = true;
                    updateCommitStatus();
                    showPayWayViewChange();
                    reCountPrice();
                }

                updateDateView();

//                reCountPrice();
            }
        });

        adapter.setOnPaymentRadioGroupListener(new CartOrderExpandListAdapter.OnRadioGroupListener() {
            @Override
            public void onRadioGroup(int groupPosition, int childPosition, int index) {
                reCountPrice();
            }
        });

        adapter.setOnDiscountListener(new CartOrderExpandListAdapter.OnDiscountListener() {
            @Override
            public void onDiscountListener(int position, String data) {

                openDiscountDialog(data);
            }
        });

        adapter.setOnMarketListener(new CartOrderExpandListAdapter.OnMarketListener() {
            @Override
            public void onMarket(MarketCart cartGoods, String marketId) {
//                requestAllFee();
                requestSigleFee(cartGoods);
            }
        });
        View header = inflaterView(R.layout.item_header_cart_order, null);
        View foot = inflaterView(R.layout.item_foot_cart_order, null);


        vTime = foot.findViewById(R.id.rl_time);

        vTime.setOnClickListener(this);

        rl_price = (RelativeLayout) foot.findViewById(R.id.rl_price);
        TextView tvTime = (TextView) foot.findViewById(R.id.tv_time);
        tvTimeDetail = (TextView) foot.findViewById(R.id.tv_time_detail);

        tvDiscountPrice = (TextView) foot.findViewById(R.id.tv_discount_price);
        tvPursePrice = (TextView) foot.findViewById(R.id.tv_purse_price);
        tvDiscount = (TextView) foot.findViewById(R.id.tv_discount);
        tvPurse = (TextView) foot.findViewById(R.id.tv_purse);
        vRight = foot.findViewById(R.id.iv_right);

        tvPay_1 = (TextView) foot.findViewById(R.id.tv_payment_2);
        tvPay_2 = (TextView) foot.findViewById(R.id.tv_payment_1);
        tvPay_1.setOnClickListener(this);
        tvPay_2.setOnClickListener(this);

        tvTitle = (TextView) header.findViewById(R.id.tv_title);
        tvDetail = (TextView) header.findViewById(R.id.tv_detail);
        tvAddressName = (TextView) header.findViewById(R.id.tv_detail_name);
        tipOverScope = header.findViewById(R.id.rl_tips);


        tvFootTotal = (TextView) foot.findViewById(R.id.tv_total);
        tvFootOtherPrice = (TextView) foot.findViewById(R.id.tv_other_price);
        View rlPre = foot.findViewById(R.id.rl_detail_price);
        View vDiscount = foot.findViewById(R.id.tv_discount);
        View vDiscountPriceRight = foot.findViewById(R.id.iv_right);
        tvFootFirst = (TextView) foot.findViewById(R.id.tv_first_price);
        tvFootLast = (TextView) foot.findViewById(R.id.tv_last_price);
        tvReduceFee = (TextView) foot.findViewById(R.id.tv_reduce_fee);
        tvReduceFeeTitle = (TextView) foot.findViewById(R.id.tv_reduce_fee_title);
        vDiscountPriceRight = foot.findViewById(R.id.iv_right);

        vDiscount.setOnClickListener(this);
        vDiscountPriceRight.setOnClickListener(this);
        tvDiscountPrice.setOnClickListener(this);

        if (preProduct != null) {
            rlPre.setVisibility(View.VISIBLE);
        } else {
            rlPre.setVisibility(View.GONE);
        }


        vAddress = header.findViewById(R.id.rl_address);
        vAddress.setOnClickListener(this);
        vEmptyAddress = header.findViewById(R.id.ll_add_address);
        vEmptyAddress.setOnClickListener(this);


        lv.addHeaderView(header);

        lv.addFooterView(foot);

        lv.setAdapter(adapter);


        if (preProduct != null) {//预售
            tvTime.setText("预计送达时间");
        } else {
            tvTime.setText("要求送达时间");
        }

        init();


    }

    public void showPayWayViewChange() {
//        if (isOffline) {
////            tvDiscountPrice.setVisibility(View.GONE);
////            vRight.setVisibility(View.GONE);
////            tvDiscount.setVisibility(View.GONE);
//            tvPursePrice.setVisibility(View.GONE);
//            tvPurse.setVisibility(View.GONE);
//        } else {
////            tvDiscountPrice.setVisibility(View.VISIBLE);
////            tvDiscount.setVisibility(View.VISIBLE);
////            vRight.setVisibility(View.VISIBLE);
//            tvPursePrice.setVisibility(View.GONE);
//            tvPurse.setVisibility(View.GONE);
//        }
        tvPursePrice.setVisibility(View.GONE);
        tvPurse.setVisibility(View.GONE);

//        if (!isPaymentOnline() || adapter.isHasSelf()) {
//            showDiscountView(false);
//        } else {
//            showDiscountView(true);
//        }
    }

    private boolean isPaymentOnline() {
        boolean isOnline = true;
        Object tag;
        if (isPaymentFirst) {
            tag = tvPay_1.getTag(R.id.item_key_id);
        } else {
            tag = tvPay_2.getTag(R.id.item_key_id);
        }
        if (!"onlinePayment".equals(tag)) {//
            isOnline = false;
        }
        return isOnline;
    }

    public void showDiscountView(boolean isShow) {
        if (isShow) {
            tvDiscountPrice.setVisibility(View.VISIBLE);
            tvDiscount.setVisibility(View.VISIBLE);
            vRight.setVisibility(View.VISIBLE);
        } else {
            tvDiscountPrice.setVisibility(View.GONE);
            vRight.setVisibility(View.GONE);
            tvDiscount.setVisibility(View.GONE);
        }
    }

    //是否可以购买
    private void updateCommitStatus() {
        //判断是否是全部自提,如果全为自提,则可直接下单

        boolean isAllSelf = false;

        boolean isOverScope = false;
        if (cartList != null) {
            List<MarketCart> wholeSaleMarketOrderList = cartList.getWholeSaleMarketOrderList();
            if (wholeSaleMarketOrderList != null && wholeSaleMarketOrderList.size() > 0) {
                isAllSelf = true;

                for (int i = 0; i < wholeSaleMarketOrderList.size(); i++) {
                    MarketCart marketCart = wholeSaleMarketOrderList.get(i);

                    if (marketCart.isDeliverySelect()) {
                        isAllSelf = false;
                        break;
                    }
                }
                for (int i = 0; i < wholeSaleMarketOrderList.size(); i++) {
                    MarketCart marketCart = wholeSaleMarketOrderList.get(i);

//                    if (marketCart.isDeliveryOverScope()) {
//                        isOverScope = true;
//                        break;
//                    }
                    if (marketCart.isOverScopeNew()) {
                        isOverScope = true;
                        break;
                    }
                }


            }

            if (address != null && isOverScope){
                tipOverScope.setVisibility(View.VISIBLE);
            }else {
                tipOverScope.setVisibility(View.GONE);
            }

            if (isAllSelf && address != null) {
                tvBtn.setEnabled(true);
            } else if (address != null && !isOverScope) {
                tvBtn.setEnabled(true);
            } else {
                tvBtn.setEnabled(false);
            }
            if (address == null) {
                tvPay_1.setEnabled(false);
                tvPay_2.setEnabled(false);
            } else {
                tvPay_1.setEnabled(true);
                tvPay_2.setEnabled(true);
            }

        }
    }

    public boolean isAllSelf() {
        boolean isAllSelf = false;
        if (cartList != null) {
            List<MarketCart> wholeSaleMarketOrderList = cartList.getWholeSaleMarketOrderList();
            if (wholeSaleMarketOrderList != null && wholeSaleMarketOrderList.size() > 0) {
                isAllSelf = true;

                for (int i = 0; i < wholeSaleMarketOrderList.size(); i++) {
                    MarketCart marketCart = wholeSaleMarketOrderList.get(i);

                    if (marketCart.isDeliverySelect()) {
                        isAllSelf = false;
                        break;
                    }
                }

            }
        }
        return isAllSelf;
    }

    public boolean isAllOnlySelf() {
        boolean isAllSelf = false;
        if (cartList != null) {
            List<MarketCart> wholeSaleMarketOrderList = cartList.getWholeSaleMarketOrderList();
            if (wholeSaleMarketOrderList != null && wholeSaleMarketOrderList.size() > 0) {
                isAllSelf = true;

                for (int i = 0; i < wholeSaleMarketOrderList.size(); i++) {
                    MarketCart marketCart = wholeSaleMarketOrderList.get(i);

                    if (!marketCart.isOnlySelf()) {
                        isAllSelf = false;
                        break;
                    }
                }

            }
        }
        return isAllSelf;
    }

    //计算价格
    private void reCountPrice() {

        double goodsPrice = adapter.getTotalGoodsPrice();
        double totalFee = adapter.getTotalFee();
        double totalRealFee = 0;
        if (deliveryDate != null) {
            if (selfFlag) {
                totalRealFee = 0.00;
                tvFootOtherPrice.setText("0.00" + "元");//getString(R.string.total_price, deliveryDate.getFreight()));
            } else {
                if (!deliveryDate.isNormalDelivery()) {
                    totalRealFee = deliveryDate.getFreight();//adapter.getRealFee();
                } else {
                    totalRealFee = adapter.getRealFee();
                }
                tvFootOtherPrice.setText(deliveryDate.getFreight() + "元");//getString(R.string.total_price, deliveryDate.getFreight()));
            }
        }
//        double totalReduceFee = adapter.getTotalReduceFee();
        double totalReduceFee = cartList.getProductExpressFeeReduce();
        //钱包
        double wallet = 0f;
        //优惠券
        double coupons = 0f;
        List<CouponEntity> couponList = null;
        if (cartList != null) {
//            wallet = cartList.getWallets();
            coupons = cartList.getCouponsPrice();
            couponList = cartList.getCouponList();
        }

        String freightFeeStr = tvFootOtherPrice.getText().toString();//运费

        double totalPrice;
//        if (isPaymentOnline() && !adapter.isHasSelf()) {
////            totalPrice = goodsPrice + factSum - wallet + coupons;
////            totalPrice = goodsPrice + totalFee + coupons;
////            totalPrice = FormatUtil.countAdd(FormatUtil.countAdd(goodsPrice, totalRealFee), coupons);
//
//
//            if (!TextUtils.isEmpty(freightFeeStr)) {
//                totalPrice = FormatUtil.countSubtract(FormatUtil.countAdd(FormatUtil.countAdd(goodsPrice, Double.valueOf(freightFeeStr.substring(0, freightFeeStr.indexOf("元")))), coupons),totalReduceFee);
//            } else {
//                totalPrice = 0f;
//            }
//        } else {
////            totalPrice = goodsPrice + totalFee;
//
//            if (!TextUtils.isEmpty(freightFeeStr)) {
////            totalPrice = FormatUtil.countAdd(goodsPrice, totalRealFee);
//                totalPrice = FormatUtil.countAdd(goodsPrice, Double.valueOf(freightFeeStr.substring(0, freightFeeStr.indexOf("元"))));
//            }
//        }



        if (!TextUtils.isEmpty(freightFeeStr)) {
            if (tvDiscountPrice.getVisibility() == View.VISIBLE && tvReduceFeeTitle.getVisibility() == View.VISIBLE){
                totalPrice = FormatUtil.countSubtract(FormatUtil.countAdd(FormatUtil.countAdd(goodsPrice, Double.valueOf(freightFeeStr.substring(0, freightFeeStr.indexOf("元")))), coupons),totalReduceFee);

            }else if (tvDiscountPrice.getVisibility() == View.VISIBLE && tvReduceFeeTitle.getVisibility() == View.GONE){
                totalPrice = FormatUtil.countAdd(FormatUtil.countAdd(goodsPrice, Double.valueOf(freightFeeStr.substring(0, freightFeeStr.indexOf("元")))), coupons);

            }else if (tvDiscountPrice.getVisibility() == View.GONE && tvReduceFeeTitle.getVisibility() == View.VISIBLE){
                totalPrice = FormatUtil.countSubtract(FormatUtil.countAdd(goodsPrice, Double.valueOf(freightFeeStr.substring(0, freightFeeStr.indexOf("元")))),totalReduceFee);

            }else {
                totalPrice = FormatUtil.countAdd(goodsPrice, Double.valueOf(freightFeeStr.substring(0, freightFeeStr.indexOf("元"))));
            }

        } else {
            totalPrice = 0f;
        }

        //商品金额
        tvFootTotal.setText(getString(R.string.total_price, goodsPrice));
        //运费金额
        //tvFootOtherPrice.setText(getString(R.string.total_price, totalFee));
        //钱包
        tvPursePrice.setText(getString(R.string.total_price, wallet));
        //优惠券
        if (couponList != null && couponList.size() > 0) {
            if (FormatUtil.remainderZero(coupons, 0) == 0) {
                tvDiscountPrice.setText("不使用优惠券");
            } else {
                tvDiscountPrice.setText(getString(R.string.total_price, coupons));
            }
        } else {
            tvDiscountPrice.setText("无可用优惠券");
        }
        //总价,优惠券,钱包,商品,运费价格总和
        tvTotal.setText(getString(R.string.total_price, totalPrice));

//        if (FormatUtil.remainderZero(totalReduceFee, 0) == 0) {
//            tvReduceFeeTitle.setVisibility(View.GONE);
//            tvReduceFee.setVisibility(View.GONE);
//            tvReduceFee.setText("-" + getString(R.string.total_price, Math.abs(totalReduceFee)));
//        } else {
//            if (!selfFlag && deliveryDate != null && deliveryDate.isNormalDelivery()) {
//                tvReduceFeeTitle.setVisibility(View.GONE);
//                tvReduceFee.setVisibility(View.GONE);
//                tvReduceFee.setText("-" + getString(R.string.total_price, Math.abs(totalReduceFee)));
//            } else {
//                tvReduceFeeTitle.setVisibility(View.GONE);
//                tvReduceFee.setVisibility(View.GONE);
//            }
//        }
        getPreStorePrice();
    }

    private void init() {

//        Log.d("goods", "----------" + new Gson().toJson(getAllGoods()) + "");

        groups.clear();
//        groups.addAll(getAllCheckedStatus());
        adapter.notifyDataSetChanged();

//        float total = adapter.calTotalPrice();
//        tvTotal.setText(getString(R.string.total_price, total));
//        tvFootTotal.setText(getString(R.string.total_price, total));

//        reCountPrice();
        //请求收货地址,然后请求页面详情
        requestDelivery();
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.baseback) {
            MobclickAgent.onEvent(this, "Click_Leave_ConfirmOrder");
        }
        super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                if (refreshFlag) {
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                }
                finish();
                break;
            case R.id.rl_address:
                Intent intent = new Intent(this, ReceiverAddressActivity.class);
                if (address != null && address.getId() != null) {
                    intent.putExtra("address_id", address.getId());
                    //isLimitArea == false 不限制区域
                    intent.putExtra("isLimitArea", false);
                    intent.putExtra("isForResult", true);
                }
                startActivityForResult(intent, 0x1993);
                break;
            case R.id.ll_add_address:
                Intent intent1 = new Intent(this, AddAddressActivity.class);
                //isLimitArea == false 不限制区域
                intent1.putExtra("isLimitArea", false);
                startActivityForResult(intent1, 0x1992);
                break;
            case R.id.tv_btn:
                MobclickAgent.onEvent(this, "Click_Submit_ConfirmOrder");

//                if (address == null) {
//                    T.toast("请选择收货地址");
//                    return;
//                }
                if (isFeeError) {
                    toast("获取运费失败,请重新选择");
                }
                if (isWindowLocked())
                    return;
                if (deliveryType.equals("商家配送")) {
                    requestOrder(getCartRequest());
                } else {
                    if (deliveryDate != null || isAllSelf()) {
                        requestOrder(getCartRequest());
                    } else {
                        openDeliveryDateDialog(false);
                    }
                }

                break;
            case R.id.righticon:
                requestAllFee();

                break;
            case R.id.tv_payment_1:
                isPaymentFirst = false;
                changePaymentStatus();
                showPayWayViewChange();
                updateColumnView();
                reCountPrice();
                break;
            case R.id.tv_payment_2:
                isPaymentFirst = true;
                changePaymentStatus();
                showPayWayViewChange();
                updateColumnView();
                reCountPrice();
                break;
            case R.id.tv_discount:
            case R.id.tv_discount_price:
            case R.id.iv_right:
                //打开购物券

                intoCouponPage();
                break;
            case R.id.rl_time:

                openDeliveryDateDialog(false);

                break;

        }
    }

    DeliveryDateNew.TimeListBean deliveryDate;
    boolean isNormalDelivery = true;
    int datePosition = 0;
    int timePosition = 0;


    private void intoTimeNew(CartList cartList) {
        List<DeliveryDateNew> deliveryDateList = cartList.getNormalDeliveryDate();
        if (deliveryDateList == null || deliveryDateList.size() == 0) {
            deliveryDateList = cartList.getExpressDeliveryDate();
            isNormalDelivery = false;
        } else {
            isNormalDelivery = true;
        }
        if (deliveryDateList == null || deliveryDateList.size() == 0) {
            selfFlag = true;
            return;
        }
        selfFlag = false;

        //      if (deliveryDateList.size() == 1) {//不需要选择
        DeliveryDateNew deliveryDateNew = deliveryDateList.get(0);
        if (deliveryDateNew != null) {
/*                String deliveryTime = deliveryDate.getTitle();
                this.deliveryDate = deliveryDate;*/
            //String deliveryTime = deliveryDate.getDateStr()+deliveryDate.getTimeList().get(0).getTitle();
            deliveryDate = deliveryDateNew.getTimeList().get(0);
            tvFootOtherPrice.setText(deliveryDate.getFreight() + "元");//getString(R.string.total_price, deliveryDate.getFreight()));

            deliveryDate.setSelectFlag(true);
            deliveryDate.setNormalDelivery(isNormalDelivery);
            deliveryDate.setDatePosition(0);
            deliveryDate.setTimePosition(0);
            deliveryDate.setFather(deliveryDateNew);
            tvTimeDetail.setText(deliveryDateNew.getDateStr() + "(" + deliveryDate.getTitle() + ")");

        }
/*        } else {
            DeliveryDateNew deliveryDate = deliveryDateList.get(0);
            if (deliveryDate != null) {
                String deliveryTime = deliveryDate.getDateStr()+deliveryDate.getTimeList().get(0).getTitle();
                this.deliveryDate = deliveryDate;
                tvTimeDetail.setText(deliveryTime);
            }

//            openDeliveryDateDialog(deliveryDateList, null, null);
        }*/

    }


/*

    private void intoTime(List<DeliveryDate> deliveryDateList) {
        if (deliveryDateList == null || deliveryDateList.size() == 0 || deliveryDate != null) {
            return;
        }

        if (deliveryDateList.size() == 1) {//不需要选择
            DeliveryDate deliveryDate = deliveryDateList.get(0);
            if (deliveryDate != null) {
                String deliveryTime = deliveryDate.getTitle();
                this.deliveryDate = deliveryDate;
                tvTimeDetail.setText(deliveryTime);
            }
        } else {
            DeliveryDate deliveryDate = deliveryDateList.get(0);
            if (deliveryDate != null) {
                String deliveryTime = deliveryDate.getTitle();
                this.deliveryDate = deliveryDate;
                tvTimeDetail.setText(deliveryTime);
            }

//            openDeliveryDateDialog(deliveryDateList, null, null);
        }

    }
*/

    private void openDeliveryDateDialog(boolean isEnsure) {
        openDeliveryDateNewDialog(cartList, null, null, isEnsure);
/*        List<DeliveryDate> deliveryDateList = cartList.getDeliveryDateList();
        if (deliveryDateList != null && deliveryDateList.size() > 0) {
*//*            String deliveryId = null;
            if (deliveryDate != null) {
                deliveryId = deliveryDate.get();
            }*//*
        }*/
    }

    private void updateDateView() {
//        List<DeliveryDate> deliveryDateList = cartList.getDeliveryDateList();
//        if (deliveryDateList != null && deliveryDateList.size() > 0) {
//            vTime.setVisibility(View.VISIBLE);
//        } else if (isAllOnlySelf()) {
//            vTime.setVisibility(View.GONE);
//        }else {
//            vTime.setVisibility(View.VISIBLE);
//        }

        if (isAllSelf()) {
            vTime.setVisibility(View.GONE);
        } else {
            //List<DeliveryDate> deliveryDateList = cartList.getDeliveryDateList(); 更改显示逻辑，从deliveryDateList>>>精准+标准
            List<DeliveryDateNew> deliveryDateList = cartList.getNormalDeliveryDate();
            if (deliveryDateList == null || deliveryDateList.size() == 0) {
                deliveryDateList = cartList.getExpressDeliveryDate();
            }
            if (deliveryDateList != null && deliveryDateList.size() > 0) {
                vTime.setVisibility(View.VISIBLE);
            } else if (isAllOnlySelf()) {
                vTime.setVisibility(View.GONE);
            } else {
                vTime.setVisibility(View.VISIBLE);
            }
        }
    }


    DeliveryDateNewDialog deliveryDateNewDialog;

    public void openDeliveryDateNewDialog(CartList cartList, DeliveryDateNew.TimeListBean bean, String distributionId, final boolean isEnsure) {
        Log.e("cartorderactivity", "dialog_________________");
        if (deliveryDateNewDialog == null) {
            deliveryDateNewDialog = new DeliveryDateNewDialog(this);
            deliveryDateNewDialog.setOnPositiveClickListener(new DeliveryDateNewDialog.OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(Object o, DeliveryDateNew.TimeListBean market) {
//                    if (o != null) {
//                        ((MarketCart) o).setDeliveryDateDef(market);
//
//                    }
                    deliveryDate = market;
                    tvTimeDetail.setText(deliveryDate.getFather().getDateStr() + "(" + deliveryDate.getTitle() + ")");
                    tvFootOtherPrice.setText(deliveryDate.getFreight() + "元");//getString(R.string.total_price, deliveryDate.getFreight()));
                    freight = market.getFreight();
                    reCountPrice();
                    if (isEnsure && deliveryDate != null) {
                        requestOrder(getCartRequest());
                    }
                }
            });
        }

//        if (deliveryDate != null) {
//            deliveryDateDialog.setCanceledOnTouchOutside(true);
//            deliveryDateDialog.setCancelable(true);
//        } else {
//            deliveryDateDialog.setCanceledOnTouchOutside(false);
//            deliveryDateDialog.setCancelable(false);
//        }

        //deliveryDateNewDialog.setO(o);
        deliveryDateNewDialog.setDates(cartList.getNormalDeliveryDate(), cartList.getExpressDeliveryDate(), deliveryDate);
        deliveryDateNewDialog.setPositiveDismiss(true);
        //deliveryDateNewDialog.setCurrent(markets, distributionId);
        if (preProduct != null) {//预售
            deliveryDateNewDialog.setTitle("预计送达时间");
        } else {
            deliveryDateNewDialog.setTitle("要求送达时间");
        }
        deliveryDateNewDialog.show();
    }




/*    DeliveryDateDialog deliveryDateDialog;

    public void openDeliveryDateDialog(List<DeliveryDate> markets, Object o, String distributionId, final boolean isEnsure) {
        Log.e("cartorderactivity","dialog_________________");
        if (deliveryDateDialog == null) {
            deliveryDateDialog = new DeliveryDateDialog(this);
            deliveryDateDialog.setOnPositiveClickListener(new DeliveryDateDialog.OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(Object o, DeliveryDate market) {
//                    if (o != null) {
//                        ((MarketCart) o).setDeliveryDateDef(market);
//
//                    }
                    String deliveryTime = market.getTitle();
                    deliveryDate = market;
                    tvTimeDetail.setText(deliveryTime);

                    if (isEnsure && deliveryDate != null) {
                        requestOrder(getCartRequest());
                    }
                }
            });
        }*/

//        if (deliveryDate != null) {
//            deliveryDateDialog.setCanceledOnTouchOutside(true);
//            deliveryDateDialog.setCancelable(true);
//        } else {
//            deliveryDateDialog.setCanceledOnTouchOutside(false);
//            deliveryDateDialog.setCancelable(false);
//        }
/*

        deliveryDateDialog.setO(o);
        deliveryDateDialog.setPositiveDismiss(true);
        deliveryDateDialog.setCurrent(markets, distributionId);
        if (preProduct != null) {//预售
            deliveryDateDialog.setTitle("预计送达时间");
        } else {
            deliveryDateDialog.setTitle("要求送达时间");
        }
        deliveryDateDialog.show();
    }
*/

    private void intoCouponPage() {
        List<CouponEntity> couponList = cartList.getCouponList();
        if (couponList != null && couponList.size() > 0) {
            Intent intent = new Intent(this, CartCouponActivity.class);
//            intent.putExtra("data", new Gson().toJson(couponList));
//            intent.putExtra("best", new Gson().toJson(cartList.getBestCoupons()));
//            intent.putExtra("select", new Gson().toJson(cartList.getSelectCoupons()));
//            intent.putExtra("storePrice", storePriceStr);
            intent.putExtra("maxCount", cartList.getCouponRemainQty());

            DataManager.getInstance().setCoupons(couponList);
            DataManager.getInstance().setCouponsBest(cartList.getBestCoupons());
            DataManager.getInstance().setCouponsSelect(cartList.getSelectCoupons());
            DataManager.getInstance().storePriceStr = storePriceStr;


            startActivityForResult(intent, 0x011);
        } else {
            Intent coupons = new Intent(this, MyCouponActivity.class);
            coupons.putExtra("isCanUse", false);
            startActivity(coupons);
        }
    }


    private String getPreStorePrice() {
        Map<String, StoreGoodsPrice> mapStorePrice = new HashMap<>();

        if (cartList != null && cartList.getWholeSaleMarketOrderList() != null && cartList.getWholeSaleMarketOrderList().size() > 0 && cartList.getWholeSaleMarketOrderList().get(0).getProductList() != null && cartList.getWholeSaleMarketOrderList().get(0).getProductList().size() > 0 && cartList.getWholeSaleMarketOrderList().get(0).getProductList().get(0) != null) {
            CartGood cartGood = cartList.getWholeSaleMarketOrderList().get(0).getProductList().get(0);
            String storeId = cartGood.getStoreId();

            if (storeId != null && !"".equals(storeId)) {

                double deposit = cartGood.getProductDeposit();
                double cnt = cartGood.getProductCount();

//                double total = cnt * cartGood.getProductUnitPrice();

//                double total = FormatUtil.countMultiply(cnt , cartGood.getProductUnitPrice());

                BigDecimal bd = new BigDecimal(cnt).multiply(new BigDecimal(cartGood.getProductUnitPrice()));
                double total = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();


                double secondPrice = FormatUtil.countSubtract(total, FormatUtil.countMultiply(deposit, cnt));
                StoreGoodsPrice storeGoodsPrice = mapStorePrice.get(storeId);
                if (storeGoodsPrice == null) {
                    storeGoodsPrice = new StoreGoodsPrice();
                }
                //将同一商店的商品累加
                storeGoodsPrice.addAllPrice(total);
                mapStorePrice.put(storeId, storeGoodsPrice);


                double totalFee = adapter.getTotalFee();
//                double totalRealFee = adapter.getRealFee();
                double totalReduceFee = adapter.getTotalReduceFee();
                double firstPrice = FormatUtil.countMultiply(deposit, cnt);
                firstPrice = FormatUtil.countAdd(firstPrice, totalFee);
                firstPrice = FormatUtil.countAdd(firstPrice, -Math.abs(totalReduceFee));
                tvFootFirst.setText(getString(R.string.total_price, firstPrice));
                tvFootLast.setText(getString(R.string.total_price, secondPrice));
            }

        }
        return new Gson().toJson(mapStorePrice);
    }

    public String getAllStoresPrice() {
        Map<String, StoreGoodsPrice> mapStorePrice = new HashMap<>();

        if (cartList != null && cartList.getWholeSaleMarketOrderList() != null && cartList.getWholeSaleMarketOrderList().size() > 0) {

            List<MarketCart> wholeSaleMarketOrderList = cartList.getWholeSaleMarketOrderList();
            for (int i = 0; i < wholeSaleMarketOrderList.size(); i++) {
                MarketCart marketCart = wholeSaleMarketOrderList.get(i);
                Integer wholeSalesType = marketCart.getWholeSalesType();
                //过滤散货
                if (wholeSalesType != 1 && !cartList.isBulkIsUsedCoupon()) {
                    continue;
                }
                if (marketCart != null && marketCart.getProductList() != null) {
                    List<CartGood> productList = marketCart.getProductList();
                    for (int j = 0; j < productList.size(); j++) {
                        CartGood cartGood = productList.get(j);
                        String storeId = cartGood.getStoreId();

                        if (storeId != null && !"".equals(storeId)) {
                            StoreGoodsPrice storeGoodsPrice = mapStorePrice.get(storeId);
                            if (storeGoodsPrice == null) {
                                storeGoodsPrice = new StoreGoodsPrice();
                            }
                            //将同一商店的商品累加
                            storeGoodsPrice.addAllPrice(cartGood.getProductTotalPrice());
                            mapStorePrice.put(storeId, storeGoodsPrice);
                        }

                    }
                }
            }

        }

        return new Gson().toJson(mapStorePrice);

    }


    public void changePaymentStatus() {
        if (isPaymentFirst) {

            tvPay_1.setBackgroundResource(R.drawable.checked_green_bg);
            tvPay_1.setTextColor(getResources().getColor(R.color.green));
            tvPay_2.setTextColor(Color.parseColor("#313131"));
            tvPay_2.setBackgroundResource(R.drawable.checked_gray_bg);
            payType = "预先支付";
        } else {

            tvPay_2.setTextColor(getResources().getColor(R.color.green));
            tvPay_1.setTextColor(Color.parseColor("#313131"));
            tvPay_1.setBackgroundResource(R.drawable.checked_gray_bg);
            tvPay_2.setBackgroundResource(R.drawable.checked_green_bg);
            payType = "货到付款";
        }
        if (address == null) {
            tvPay_1.setBackgroundResource(R.drawable.enable_tag_bg);
            tvPay_2.setBackgroundResource(R.drawable.enable_tag_bg);
            tvPay_2.setTextColor(Color.parseColor("#ffffff"));
            tvPay_1.setTextColor(Color.parseColor("#ffffff"));
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 0x1992 && data != null) {
            String addressStr = data.getStringExtra("address");
            Address address = new Gson().fromJson(addressStr, Address.class);
            adapter.setHasAddress(false);
            if (address != null && address.getName() != null && !"".equals(address.getName())) {

                adapter.setHasAddress(true);
                this.address = address;
                requestOrderGenerateBefore(getAllGoods(), address);

                String name = address.getName();
                String phone = address.getPhone();
                addressStr = address.getAddressStr();
                tvTitle.setText(name + "    " + phone);
                tvDetail.setText(addressStr);
//                tvAddressName.setText(getUser().getNickname());

                vAddress.setVisibility(View.VISIBLE);
                vEmptyAddress.setVisibility(View.GONE);


            } else {
                requestOrderGenerateBefore(getAllGoods(), address);
            }
            updateCommitStatus();
        } else if (resultCode == RESULT_OK && requestCode == 0x1993 && data != null) {
            String addressStr = data.getStringExtra("address");
            boolean isEmpty = data.getBooleanExtra("is_empty", false);
            adapter.setHasAddress(false);
            if (isEmpty) {
                address = null;
                vAddress.setVisibility(View.GONE);
                vEmptyAddress.setVisibility(View.VISIBLE);
                requestOrderGenerateBefore(getAllGoods(), null);
            }
            if (addressStr != null && !"".equals(addressStr)) {
                Address address = new Gson().fromJson(addressStr, Address.class);

                if (address != null && address.getName() != null && !"".equals(address.getName())) {
                    //选择了相同的地址

                    adapter.setHasAddress(true);
                    if (this.address != null && this.address.getId() != null && this.address.getId().equals(address.getId())) {
                        String lat = address.getLat();
                        String lng = address.getLng();
                        if (lat != null && lng != null && lat.equals(this.address.getLat()) && lng.equals(this.address.getLng())) {

                        } else {//更新地址
                            requestOrderGenerateBefore(getAllGoods(), address);
                        }
                        this.address = address;

                    } else {
                        this.address = address;
                        requestOrderGenerateBefore(getAllGoods(), address);
                    }

                    String name = address.getName();
                    String phone = address.getPhone();
                    addressStr = address.getAddressStr();
                    tvTitle.setText(name + "    " + phone);
                    tvDetail.setText(addressStr);
//                    tvAddressName.setText(getUser().getNickname());
                    vAddress.setVisibility(View.VISIBLE);
                    vEmptyAddress.setVisibility(View.GONE);

                }
            }
            updateCommitStatus();
        } else if (resultCode == RESULT_OK && requestCode == 0x011 && data != null) {

//            String result = data.getStringExtra("result");
//            String select = data.getStringExtra("select");
//            if (result != null && !"".equals(result)) {
//                ArrayList<CouponEntity> couponEntities = new Gson().fromJson(result, new TypeToken<List<CouponEntity>>() {
//                }.getType());
//                ArrayList<CouponEntity> couponSelect = new Gson().fromJson(select, new TypeToken<List<CouponEntity>>() {
//                }.getType());
            List<CouponEntity> couponEntities = DataManager.getInstance().coupons;
            List<CouponEntity> couponSelect = DataManager.getInstance().couponsSelect;
            DataManager.getInstance().coupons = null;
            DataManager.getInstance().couponsSelect = null;
            DataManager.getInstance().couponsBest = null;
            DataManager.getInstance().storePriceStr = null;
//            Log.e("list","2:"+couponEntities+"");
            if (couponEntities != null && couponEntities.size() > 0) {
                cartList.setCouponList(couponEntities);
                cartList.setSelectCouponList(couponSelect);
                reCountPrice();

            }
//            }

        }
    }

    public List<CartGoods> getAllCheckedStatus() {
        List<CartGoods> listChecked = new ArrayList<>();
        List<CartGoods> groupList = DataManager.getInstance().getCloneCartGoods();

        for (int j = 0; j < groupList.size(); j++) {

            CartGoods cartGoods = groupList.get(j);


            if (cartGoods.isDisabled()) {
                continue;
            }

            List<CartGood> list = cartGoods.getResult();
            if (list != null && list.size() > 0) {
                List<CartGood> list1 = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    CartGood cartGood = list.get(i);
                    if (cartGood.isSelect() && cartGood.isCheckCityId()) {
                        list1.add(cartGood);
                    }
                }
                if (list1.size() > 0) {
                    cartGoods.setDeliveryDateDef(cartGoods.getDefDeliveryDate());
                    cartGoods.setResult(list1);
                    listChecked.add(cartGoods);
                }
            }
        }

        return listChecked;
    }

    //请求购物车详情
    public List<Map<String, Object>> getAllGoods() {
//        List<CartGoods> listChecked = new ArrayList<>();
        Map<String, Object> listReq = null;// = new ArrayList<>();
        List<Map<String, Object>> listReturn = new ArrayList<>();
        if (preProduct == null) {
            List<CartGoods> groupList = DataManager.getInstance().getCloneCartGoods();

            for (int j = 0; j < groupList.size(); j++) {

                CartGoods cartGoods = groupList.get(j);


                if (cartGoods.isDisabled()) {
                    continue;
                }

                List<CartGood> list = cartGoods.getResult();
                if (list != null && list.size() > 0) {
//                List<CartGood> list1 = new ArrayList<>();
                    List<Map<String, Object>> list0 = new ArrayList<>();
//                    private Long promotionItemId;//促销场次ID
//                    private Long promotionId;//促销ID
//                    private Integer promotionType
                    for (int i = 0; i < list.size(); i++) {
                        CartGood cartGood = list.get(i);
                        if (cartGood.isSelect() && cartGood.isCheckCityId()) {
                            Map<String, Object> map = new HashMap<>();
//                            map.put("specId", cartGood.getProductId());
                            map.put("specId", cartGood.getSpecId());
                            map.put("productCount", cartGood.getProductCount());
                            map.put("salesType", cartGood.getSalesType());
                            map.put("versionId", cartGood.getVersionId());
//                            map.put("shoppingCarId", cartGood.getId());
                            map.put("shoppingCarId", cartGood.getId());
                            map.put("promotionItemId", cartGood.getPromotionItemId());
                            map.put("promotionId", cartGood.getPromotionId());
                            map.put("promotionType", cartGood.getPromotionType());

                            cartMap.put(cartGood.getShoppingCarId() + "", cartGood);
                            list0.add(map);

                        }
                    }
                    listReturn = list0;

                   /* if (list0.size() > 0) {

                        Map<String, Object> map = new HashMap<>();
                        map.put("wholeSaleMarketId", cartGoods.getWholeSaleMarketId());
                        map.put("wholeSalesType", cartGoods.getWholeSalesType());
                        map.put("list", list0);
                        listReq=(map);

                    }*/
                }
            }

            return listReturn;
        } else {
/*            Map<String, Object> map = new HashMap<>();
            map.put("wholeSaleMarketId", marketId);
            map.put("wholeSalesType", 1);
            List<Map<String, Object>> list = new ArrayList<>();
            list.add(preProductMap);
            map.put("list", list);
            listReq.add(map);*/
            List<Map<String, Object>> list = new ArrayList<>();
            list.add(preProductMap);
            return list;
        }
    }


    public String getAllStores() {
        Map<String, StoreGoodsPrice> mapStorePrice = new HashMap<>();
        List<CartGoods> groupList = DataManager.getInstance().getCloneCartGoods();

        for (int j = 0; j < groupList.size(); j++) {

            CartGoods cartGoods = groupList.get(j);


            if (cartGoods.isDisabled()) {
                continue;
            }

//            //过滤散货
//            if (cartGoods.getWholeSalesType() != 1){
//                continue;
//            }
            List<CartGood> list = cartGoods.getResult();
            if (list != null && list.size() > 0) {
//                List<CartGood> list1 = new ArrayList<>();
                List<Map<String, Object>> list0 = new ArrayList<>();

                for (int i = 0; i < list.size(); i++) {
                    CartGood cartGood = list.get(i);
                    if (cartGood.isSelect() && cartGood.isCheckCityId()) {

                        String storeId = cartGood.getStoreId();

                        if (storeId != null && !"".equals(storeId)) {
                            StoreGoodsPrice storeGoodsPrice = mapStorePrice.get(storeId);
                            if (storeGoodsPrice == null) {
                                storeGoodsPrice = new StoreGoodsPrice();
                            }
                            //将同一商店的商品累加
                            storeGoodsPrice.addAllPrice(cartGood.getProductTotalPrice());
                            mapStorePrice.put(storeId, storeGoodsPrice);
                        }


                    }
                }

            }
        }


        return new Gson().toJson(mapStorePrice);

    }


    //下单入参
    public List<CartRequest> getCartRequest() {
        List<CartRequest> list0 = new ArrayList<>();
        for (int j = 0; j < groups.size(); j++) {
            MarketCart cartGoods = groups.get(j);
            List<CartGood> list = cartGoods.getProductList();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    CartGood cartGood = list.get(i);
                    CartRequest cr = new CartRequest();
                    CartGood cg = cartMap.get(cartGood.getShoppingCarId() + "");
                    if (cg != null)
                        cr.setCarNo(cg.getCarNo());
                    cr.setShoppingCarId(cartGood.getShoppingCarId());
                    cr.setSpecId(cartGood.getSpecId());
                    cr.setPromotionItemId(cartGood.getPromotionItemId());
                    cr.setProductCount(cartGood.getProductCount());
                    cr.setProductUnitPrice(cartGood.getProductUnitPrice() + "");
                    if (cartGood.getSalesType().equals("2")) {
                        cr.setMerMsg(cartGood.getMerMsg());
                    }
                    cr.setSpecModefiedTime(cartGood.getSpecModefiedTime());
                    //cr.setSpecModefiedTime(cartGood.g()); todo;2018年11月14日19:08:34
//                    cr.setMerMsg(cartGood.getShoppingCarId());
/*
                    cr.setWholeSalesType(cartGood.getWholeSalesType());
                    cr.setPromotionId(cartGood.getPromotionId());
                    cr.setPromotionItemId(cartGood.getPromotionItemId());
                    cr.setPromotionType(cartGood.getPromotionType());
                    if (address != null) {
                        cr.setReceiverDetailsAddress(address.getAddressOnMap());
                        cr.setReceiverDetailsAddressx(address.getAddress());
                        cr.setLatitude(address.getLat());
                        cr.setLongitude(address.getLng());

                        cr.setReceiverProvinceId(address.getProvinceId());
                        cr.setReceiverCityId(address.getCityId());
                        cr.setReceiverDistrictId(address.getDistrictId());
                        cr.setReceiverStreetId(address.getStreetId());
                        cr.setReceiver(address.getName());
                        cr.setReceiverPhone(address.getPhone());
                    }
                    //选择配送时间
                    if (deliveryDate != null) {
                        cr.setDeliveryDateTypeAndId(deliveryDate.getTypeAndId());
                        cr.setDeliveryDateStr(deliveryDate.getTitle());
                    }

                    cr.setDeliveryTypeStr(cartGoods.getDeliveryMode());
                    cr.setDistributionId(cartGoods.getDistributionId());
                    cr.setWholeSaleMarketId(cartGoods.getWholeSaleMarketId());
                    cr.setSpecId(cartGood.getProductSpecId() + "");
                    cr.setShoppingCarId(cartGood.getShoppingCarId() + "");
                    cr.setProductCount(cartGood.getProductCount());
                    cr.setVersionId(cartGood.getVersionId() + "");
                    cr.setProductUnitPrice(cartGood.getProductUnitPrice() + "");
                    cr.setPickupId(cartGood.getPickupId() + "");
                    cr.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
                    cr.setAccountId(ApplicationHelper.getInstance().getUser().getAccountId());

                    cr.setSalesType(cartGood.getSalesType());
                    if (isPaymentFirst) {
                        List<PaymentModes> payTypeList = cartList.getPayTypeList();
                        String code = "onlinePayment";
                        if (payTypeList != null && payTypeList.size() > 0) {
                            PaymentModes paymentModes = payTypeList.get(0);
                            if (paymentModes != null) {
                                code = paymentModes.getCode();
                                if (code == null || "".equals(code)) {
                                    code = "onlinePayment";
                                }
                            }
                        }
                        cr.setPayTypeStr(code);
                    } else {
                        List<PaymentModes> payTypeList = cartList.getPayTypeList();
                        String code = "cashOnDelivery";
                        if (payTypeList != null && payTypeList.size() > 1) {
                            PaymentModes paymentModes = payTypeList.get(1);
                            if (paymentModes != null) {
                                code = paymentModes.getCode();
                                if (code == null || "".equals(code)) {
                                    code = "cashOnDelivery";
                                }
                            }
                        }
                        cr.setPayTypeStr(code);
                    }
                    cr.setSupplyChannelStr("supplierExpress");
                    cr.setVersionId(cartGood.getVersionId() + "");
                    cr.setProductUnitPrice(cartGood.getProductUnitPrice() + "");
                    cr.setMerMsg(cartGood.getMerMsg());
                    if (cartList != null) {
                        if (isPaymentFirst) {
//                            cr.setWallets(cartList.getWallets() + "");
                            cr.setWallets("0");
                        } else {
                            cr.setWallets("0");

                        }
                    }*/
                    list0.add(cr);
                }


            }
        }


        return list0;
    }

    //请求所有商品运费
    public FeedRequest getAllFeedRequest(Address address) {
        FeedRequest cr = null;

        for (int j = 0; j < groups.size(); j++) {

            MarketCart cartGoods = groups.get(j);


            List<CartGood> list = cartGoods.getProductList();
            if (list != null && list.size() > 0) {
                List<Map<String, Object>> ids = null;

                for (int i = 0; i < list.size(); i++) {
                    CartGood cartGood = list.get(i);

                    if (cartGood.getWholeSalesType() == 2) {
                        //散货

                    } else {
                        if (cr == null) {
                            cr = new FeedRequest();
                            ids = new ArrayList<>();
//                            cr.setOriginRegion(ApplicationHelper.getInstance().getCity().getCityName());
                            cr.setDestination(address.getCityName());
                            cr.setReceiverDetailsAddress(address.getAddressOnMap());
                            cr.setReceiverDetailsAddressx(address.getAddress());
                            cr.setWholeSaleMarketId(cartGoods.getWholeSaleMarketId());

                            cr.setWholeSalesType(cartGoods.getWholeSalesType());
                            cr.setLongitude(address.getLng());
                            cr.setLatitude(address.getLat());
                            cr.setDistributionId(cartGoods.getDistributionId());
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("specId", cartGood.getProductId());
                        map.put("shoppingCarId", cartGood.getId());
                        map.put("productCount", cartGood.getProductCount());
                        map.put("promotionItemId", cartGood.getPromotionItemId());
                        ids.add(map);
                    }
                }


                if (cr != null && cartGoods.getDistributionId() != null && !"".equals(cartGoods.getDistributionId())) {
                    cr.setList(ids);
                    //list0.add(cr);
                }

            }
        }


        return cr;
    }

    public FeedRequest getSigleFeedRequest(Address address, MarketCart cartGoods) {
        //List<FeedRequest> list0 = new ArrayList<>();

        FeedRequest cr = null;

        List<CartGood> list = cartGoods.getProductList();
        if (list != null && list.size() > 0) {
            List<Map<String, Object>> ids = null;

            for (int i = 0; i < list.size(); i++) {
                CartGood cartGood = list.get(i);

                if (cartGood.getWholeSalesType() == 2) {
                    //散货

                } else {
                    if (cr == null) {
                        cr = new FeedRequest();
                        ids = new ArrayList<>();
//                            cr.setOriginRegion(ApplicationHelper.getInstance().getCity().getCityName());
                        cr.setDestination(address.getCityName());
                        cr.setReceiverDetailsAddress(address.getAddressOnMap());
                        cr.setReceiverDetailsAddressx(address.getAddress());
                        cr.setWholeSaleMarketId(cartGoods.getWholeSaleMarketId());

                        cr.setWholeSalesType(cartGoods.getWholeSalesType());
                        cr.setLongitude(address.getLng());
                        cr.setLatitude(address.getLat());
                        cr.setDistributionId(cartGoods.getDistributionId());
                    }
                    Map<String, Object> map = new HashMap<>();
//                    map.put("specId", cartGood.getProductId());
                    map.put("specId", cartGood.getSpecId());
                    map.put("shoppingCarId", cartGood.getId());
                    map.put("productCount", cartGood.getProductCount());
                    map.put("promotionItemId", cartGood.getPromotionItemId());
                    ids.add(map);
                }
            }


            if (cr != null && cartGoods.getDistributionId() != null && !"".equals(cartGoods.getDistributionId())) {
                cr.setList(ids);
                //list0.add(cr);
            }

        }


        return cr;
    }

    //更新运费
    private void updateFeed(List<Feed> feeds) {
        Map<String, Feed> map = new HashMap<>();
        double fee = 0;
        Log.e("feed", "feeds:" + feeds);
        for (int i = 0; i < feeds.size(); i++) {
            Feed feed = feeds.get(i);


            if (feed.getWholeSalesType() == 1) {

                map.put(feed.getWholeSaleMarketId(), feed);
                fee = FormatUtil.countAdd(fee, feed.getProductExpressFee());
//                fee += feed.getProductExpressFee();
            }
        }


        for (int i = 0; i < groups.size(); i++) {
            MarketCart cartGoods = groups.get(i);
            Feed feed = map.get(cartGoods.getWholeSaleMarketId());

            if (feed != null && cartGoods.getWholeSalesType() == 1) {
                cartGoods.setFeed(feed.getProductExpressFee());

                cartGoods.setProductExpressFee(feed.getProductExpressFee());
                cartGoods.setProductExpressFeeOriginal(freight);
                cartGoods.setProductExpressFeeReduce(feed.getProductExpressFeeReduce());
                cartGoods.setProductExpressFeeStartingPrice(feed.getProductExpressFeeStartingPrice());
            }
        }

//        float factSum = adapter.getTotalFee();
//        tvFootOtherPrice.setText(getString(R.string.total_price, factSum));
//        tvOtherPrice.setText(getString(R.string.include_fee_price, factSum));

        reCountPrice();
        adapter.notifyDataSetChanged();
    }

    public void requestAllFee() {
        if (address != null) {
            FeedRequest feedRequest = getAllFeedRequest(address);
            requestFeed(feedRequest);
        } else {
            updateCommitStatus();
        }
    }

    public void requestSigleFee(MarketCart cartGoods) {
        if (address != null) {
            FeedRequest feedRequest = getSigleFeedRequest(address, cartGoods);
            requestFeed(feedRequest);
        } else {
            updateCommitStatus();
        }
    }

    OnRequestListener<List<Address>> onRequestAddressListener = new OnRequestListener<List<Address>>() {
        @Override
        public List<Address> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<Address>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            showExceptionView(R.mipmap.order_no, "获取数据失败,请重试", 1);
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            showExceptionView(R.mipmap.order_no, o + "", 1);
        }

        @Override
        public void onStart(Object o) {

            showProgressView();
        }

        @Override
        public void onResponse(ResponseEntity<List<Address>> responseEntity, Object o) {

            showMainView();
            adapter.setHasAddress(false);
            List<Address> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

                if (responseElement.size() > 0) {
//                    for (int i=0;i<responseElement.size();i++) {
//                        Address address = responseElement.get(i);
//                        if (address != null && address.isDefault()) {
//                            CartOrderActivity.this.address = address;
//                            String name = address.getName();
//                            String phone = address.getPhone();
//
//                            String addressStr = address.getAddressStr();
//
//
//                            tvTitle.setText(name + "    " + phone);
//                            tvDetail.setText(addressStr);
//
//                            vAddress.setVisibility(View.VISIBLE);
//                            vEmptyAddress.setVisibility(View.GONE);
//                            tvBtn.setEnabled(true);
//                            requestAllFee();
//                            return;
//                        }
//                    }
                    Address address = responseElement.get(0);
                    if (address != null) {
                        CartOrderNewActivity.this.address = address;
                        String name = address.getName();
                        String phone = address.getPhone();
                        adapter.setHasAddress(true);
                        String addressStr = address.getAddressStr();


                        tvTitle.setText(name + "    " + phone);
                        tvDetail.setText(addressStr);
//                        tvAddressName.setText(getUser().getNickname());
                        vAddress.setVisibility(View.VISIBLE);
                        vEmptyAddress.setVisibility(View.GONE);

//                        requestAllFee();
                        requestOrderGenerateBefore(getAllGoods(), address);
                        return;
                    }
                } else {
                    vAddress.setVisibility(View.GONE);
                    vEmptyAddress.setVisibility(View.VISIBLE);
                    adapter.setHasAddress(false);
                    requestOrderGenerateBefore(getAllGoods(), address);
                    return;
                }

            }

            showExceptionView(R.mipmap.order_no, "数据获取失败,请重试", 1);
        }
    };

    public void requestDelivery() {

        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_list);

        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
//        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());


        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_address_list, onRequestAddressListener);

    }


    public void requestOrder(List<CartRequest> carts) {
        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_order_create);


        re.putParameter("list", carts);
        if (address != null) {
            re.putParameter("addressId", address.getId());
        }

        if (isPaymentOnline()) {
            re.putParameter("couponsList", cartList.getCoupons());
        }
/*
        re.putParameter("wholeSalesType",cartGood.getWholeSalesType());
        re.putParameter("wholeSalesType",cartGood.getWholeSalesType());
        re.putParameter("wholeSalesType",cartGood.getWholeSalesType());
        re.putParameter("wholeSalesType",cartGood.getWholeSalesType());
        re.putParameter("wholeSalesType",cartGood.getWholeSalesType());
        re.putParameter("wholeSalesType",cartGood.getWholeSalesType());*/
        if (address != null) {
            re.putParameter("receiverDetailsAddress", address.getAddressOnMap());
            re.putParameter("receiverDetailsAddressx", address.getAddress());
            re.putParameter("latitude", address.getLat());
            re.putParameter("longitude", address.getLng());
            re.putParameter("receiverProvinceId", address.getProvinceId());
            re.putParameter("receiverCityId", address.getCityId());
            re.putParameter("receiverDistrictId", address.getDistrictId());
            re.putParameter("receiverStreetId", address.getStreetId());
            re.putParameter("receiver", address.getName());
            re.putParameter("receiverPhone", address.getPhone());

        }/*
            cr.setReceiverDetailsAddress(address.getAddressOnMap());
            cr.setReceiverDetailsAddressx(address.getAddress());
            cr.setLatitude(address.getLat());
            cr.setLongitude(address.getLng());

            cr.setReceiverProvinceId(address.getProvinceId());
            cr.setReceiverCityId(address.getCityId());
            cr.setReceiverDistrictId(address.getDistrictId());
            cr.setReceiverStreetId(address.getStreetId());
            cr.setReceiver(address.getName());
            cr.setReceiverPhone(address.getPhone());
        }*/
        //选择配送时间
        if (deliveryDate != null) {
            re.putParameter("deliveryDateTypeAndId", deliveryDate.getTypeAndId());
            re.putParameter("deliveryDateStr", deliveryDate.getTitle());
        }
/*            cr.setDeliveryDateTypeAndId(deliveryDate.getTypeAndId());
            cr.setDeliveryDateStr(deliveryDate.getTitle());*/
        re.putParameter("deliveryTypeStr", groups.get(0).getDeliveryMode());
        re.putParameter("distributionId", groups.get(0).getDistributionId());
        re.putParameter("wholeSaleMarketId", groups.get(0).getWholeSaleMarketId());
        //re.putParameter("pickupId",groups.get(0).getPickupId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
/*        cr.setDeliveryTypeStr(cartGoods.getDeliveryMode());
        cr.setDistributionId(cartGoods.getDistributionId());
        cr.setWholeSaleMarketId(cartGoods.getWholeSaleMarketId());
        cr.setPickupId(cartGood.getPickupId() + "");
        cr.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
        cr.setAccountId(ApplicationHelper.getInstance().getUser().getAccountId());

        cr.setSalesType(cartGood.getSalesType());*/
        if (isPaymentFirst) {
            List<PaymentModes> payTypeList = cartList.getPayTypeList();
            String code = "onlinePayment";
            if (payTypeList != null && payTypeList.size() > 0) {
                PaymentModes paymentModes = payTypeList.get(0);
                if (paymentModes != null) {
                    code = paymentModes.getCode();
                    if (code == null || "".equals(code)) {
                        code = "onlinePayment";
                    }
                }
            }
            re.putParameter("payTypeStr", code);
            //cr.setPayTypeStr(code);
        } else {
            List<PaymentModes> payTypeList = cartList.getPayTypeList();
            String code = "cashOnDelivery";
            if (payTypeList != null && payTypeList.size() > 1) {
                PaymentModes paymentModes = payTypeList.get(1);
                if (paymentModes != null) {
                    code = paymentModes.getCode();
                    if (code == null || "".equals(code)) {
                        code = "cashOnDelivery";
                    }
                }
            }
            re.putParameter("payTypeStr", code);
            // cr.setPayTypeStr(code);
        }
/*        cr.setSupplyChannelStr("supplierExpress");
        cr.setVersionId(cartGood.getVersionId() + "");
        cr.setProductUnitPrice(cartGood.getProductUnitPrice() + "");
        cr.setMerMsg(cartGood.getMerMsg());*/
        if (cartList != null) {
            if (isPaymentFirst) {
//                            cr.setWallets(cartList.getWallets() + "");
                //cr.setWallets("0");
                re.putParameter("wallets", "0");
            } else {
                //cr.setWallets("0");
                re.putParameter("wallets", "0");

            }
        }


        RequestTag rt = new RequestTag();
        rt.type = RequestTag.TYPE_CURRENT;
        rt.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_order_create;
        request(re, rt, onRequestOrderListener);
    }

    OnRequestListener<CreateOrderBean> onRequestOrderListener = new OnRequestListener<CreateOrderBean>() {
        @Override
        public CreateOrderBean jsonToObj(String s) {
            return new Gson().fromJson(s, CreateOrderBean.class);
        }

        @Override
        public void onFail(int failCode, Object o, Object o1) {
            if (failCode != HttpRequest.FAIL_NO_NET) {
                com.epfresh.api.utils.T.toast(ApplicationHelper.getInstance().getDoc().getNetWeak());
            }
            hideProgressDialog();
            tvBtn.setEnabled(true);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object o1) {
//            410, "不能选购自己店铺的商品！"
//            407, "商品库存不足，请选购其它商品！
//            408, "商品信息已更新，请刷新！
            //443 所选时间段已无法配送 刷新
            hideProgressDialog();

            if (failCode == 407 || failCode == 408) {
                if (arg != null && !"".equals(arg)) {
                } else {
                    arg = "商品信息变化,请重新选择";
                }
                openOrderFailDialog(arg + "");
            } else if (failCode == 443) {
                com.epfresh.api.utils.T.toast("" + arg);
                requestOrderGenerateBefore(getAllGoods(), address);
            } else {
                com.epfresh.api.utils.T.toast("" + arg);
            }

            tvBtn.setEnabled(true);
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
            tvBtn.setEnabled(false);

        }

        @Override
        public void onResponse(ResponseEntity<CreateOrderBean> responseEntity, Object o) {
            //batchNo;type:1.货到付款,2在线支付
            tvBtn.setEnabled(true);
            DataManager.getInstance().oftenListReFresh = true;
            hideProgressDialog();
            CreateOrderBean responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                String batchNo = responseElement.getBatchNo();
                String type = responseElement.getType();
                boolean cashFlag = responseElement.isShowCashFlag();

                if (batchNo != null) {


                    if (!cashFlag) {//无需支付
                        DataManager.getInstance().isNeedRefreshCart = true;
                        Intent intent = new Intent(CartOrderNewActivity.this, OrderSuccessActivity.class);
                        intent.putExtra("logisticsNo", batchNo);
                        intent.putExtra("noNeedPay", true);
                        startActivity(intent);
                        finish();

                    } else {//支付
                        DataManager.getInstance().isNeedRefreshCart = true;
                        Intent intent = new Intent(CartOrderNewActivity.this, WXPayEntryActivity.class);
                        intent.putExtra("logisticsNo", batchNo);
                        intent.putExtra("payWayType", 1);

                        if (preProduct != null) {//预售
                            intent.putExtra("payWay", 2);
                        } else {
                            intent.putExtra("payWay", 1);
                        }

                        startActivity(intent);
                        finish();
                    }
                    if (address != null) {
                        String id = address.getId();
                        DataManager.getInstance().updateAddressCnt(id);
                    }
                }


            }

        }
    };

    OnRequestListener<CartList> onRequestOrderGenerateBeforeListener = new OnRequestListener<CartList>() {
        @Override
        public CartList jsonToObj(String s) {
            Log.e("ESD", "获取的s=" + s);
            CartList c = new Gson().fromJson(s, CartList.class);
            List<CartGood> productList;
            if (c != null) {
                productList = c.getProductList();
            } else {
                productList = null;
            }

            if (productList != null) {
                for (int j = 0; j < productList.size(); j++) {
                    CartGood cartGood = productList.get(j);
                    if (cartGood != null) {
                        String productId = cartGood.getShoppingCarId();
                        String s1 = mapMsg.get(productId);
                        if (TextUtils.isEmpty(s1)) {
                            cartGood.setMerMsg(cartGood.getMerMsg());
                        } else {
                            cartGood.setMerMsg(s1);
                        }
//                        cartGood.setMerMsg(s1);
                    }
                }
            } else {
                return c;
            }
            List<MarketCart> marketCarts = new ArrayList<>();
            MarketCart marketCart = new MarketCart();
            for (CartGood good : productList) {
                good.setSalesType(String.valueOf(c.getSalesType()));
            }
            marketCart.setOverScopeNew(c.isOverScope());
            marketCart.setProductList(productList);
            marketCart.setWholeSalesType(c.getWholeSalesType());
            marketCart.setDeliveryDateDef(c.getDeliveryDateDef());
            marketCart.setDeliveryDateList(c.getDeliveryDateList());
            marketCart.setDeliveryList(c.getDeliveryList());
            marketCart.setDeliverySelect(c.isDeliverySelect());
            marketCart.setDiscountStr(c.getDiscountStr());
            marketCart.setDistributionId(c.getDistributionId());
            marketCart.setDistributionList(c.getDistributionList());
            marketCart.setDistributionName(c.getDistributionName());
            marketCart.setDistributionTitle(c.getDistributionTitle());
            marketCart.setEconomizePrice(c.getEconomizePrice());
            marketCart.setExpend(c.isExpend());
            marketCart.setFeed(c.getFeed());
            //marketCart.setOverScope(c.isExpend());
            marketCart.setProductExpressFee(c.getProductExpressFee());
            if (c.getNormalDeliveryDate() != null && c.getNormalDeliveryDate().size() != 0) {
                freight = c.getNormalDeliveryDate().get(0).getTimeList().get(0).getFreight();
            }
            marketCart.setProductExpressFeeOriginal(c.getProductExpressFeeOriginal());
            marketCart.setProductExpressFeeReduce(c.getProductExpressFeeReduce());
            marketCart.setWholeSaleMarketFullName(c.getWholeSaleMarketFullName());
            marketCart.setWholeSaleMarketId(c.getWholeSaleMarketId());
            marketCart.setStoreOrMarketName(c.getStoreOrMarketName());
            marketCart.setProductExpressFeeStartingPrice(c.getProductExpressFeeStartingPrice());
            marketCart.setSalesType(String.valueOf(c.getSalesType()));
            marketCarts.clear();
            marketCarts.add(marketCart);
            c.setWholeSaleMarketOrderList(marketCarts);

/*            if (c != null && !mapMsg.isEmpty()){
                List<MarketCart> marketCarts = c.getWholeSaleMarketOrderList();
                if (marketCarts != null && marketCarts.size()>0){
                    for (int i = 0;i<marketCarts.size();i++){
                        MarketCart marketCart = marketCarts.get(i);
                        if (marketCart != null){
                            List<CartGood> productList = marketCart.getProductList();
                            if (productList != null){
                                for (int j =0 ;j<productList.size();j++){
                                    CartGood cartGood = productList.get(j);
                                    if (cartGood != null){
                                        String productId = cartGood.getShoppingCarId();
                                        String s1 = mapMsg.get(productId);
                                        cartGood.setMerMsg(s1);
                                    }


                                }
                            }
                        }
                    }
                }
            }*/
            return c;
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
//            showExceptionView(R.mipmap.order_no, "获取数据失败,请重试", 1);

            if (o != null && !"".equals(o)) {
                Log.e("ESD", "onFail()-->o.toString()=" + o.toString());
                showExceptionView(R.mipmap.order_no, o.toString(), 1);
            } else if (o1 != null && !"".equals(o1)) {
                Log.e("ESD", "onFail()-->o1.toString()=" + o1.toString());
            } else {
                showExceptionView(R.mipmap.order_no, "onFail", 1);
            }
        }

        @Override
        public void onResponseError(int failCode, Object o, Object o1) {
//            if (failCode == 407 || failCode == 408) {
//                if (o != null && !"".equals(o)) {
//                }else {
//                    o = "商品信息变化,请重新选择";
//                }
//                openOrderFailDialog(o + "");
//            } else {
//                showExceptionView(R.mipmap.order_no, o + "", 1);
//            }

            if (o != null && !"".equals(o)) {
                Log.e("ESD", "onResponseError()-->o=" + o);
                showExceptionView(R.mipmap.order_no, o + "", 1);
            } else if (o1 != null && !"".equals(o1)) {
                Log.e("ESD", "onResponseError()-->o1=" + o1);
            } else {
                showExceptionView(R.mipmap.order_no, "onResponseError", 1);
            }


        }

        @Override
        public void onStart(Object o) {

            showProgressView();


        }

        @Override
        public void onResponse(ResponseEntity<CartList> responseEntity, Object o) {


            showMainView();
            CartList responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                cartList = responseElement;
                //List<DeliveryDate> deliveryDateList = cartList.getDeliveryDateList();

                intoTimeNew(responseElement);


                List<MarketCart> wholeSaleMarketOrderList = responseElement.getWholeSaleMarketOrderList();
                groups.clear();
                if (cartList != null) {
                    cartList.initBestCoupons();
                    cartList.initSelectCoupons();
                    //没有市场
                    if (wholeSaleMarketOrderList == null || wholeSaleMarketOrderList.size() == 0) {
                        openOrderFailDialog("商品信息变化,请重新选择");
                    }
                } else {
                    //没有市场
                    openOrderFailDialog("商品信息变化,请重新选择");
                }
                if (wholeSaleMarketOrderList != null) {

                    for (int i = 0; i < wholeSaleMarketOrderList.size(); i++) {
                        wholeSaleMarketOrderList.get(i).initDistribution();
                    }
                    groups.addAll(wholeSaleMarketOrderList);
                    for (int i = 0; i < groups.size(); i++) {
                        List<CartGood> productList = groups.get(i).getProductList();
                        if (productList != null && productList.size() > 0) {
                            if (productList.get(0).isPrePrice()) {
                                rl_price.setVisibility(View.VISIBLE);
                                tvTotal.setVisibility(View.VISIBLE);
                                tv_total_name.setVisibility(View.VISIBLE);
                            } else {
                                rl_price.setVisibility(View.GONE);
                                tvTotal.setVisibility(View.GONE);
                                tv_total_name.setVisibility(View.GONE);
                            }
                        }

                    }

                    Log.e("groups", "groups:" + new Gson().toJson(groups));
                }
                List<PaymentModes> payTypeList = cartList.getPayTypeList();
                tvPay_1.setVisibility(View.GONE);
                tvPay_2.setVisibility(View.GONE);
                for (int i = 0; i < payTypeList.size(); i++) {
                    PaymentModes paymentModes = payTypeList.get(i);

                    if (i == 0 && paymentModes != null) {
                        tvPay_1.setText(paymentModes.getName());
                        tvPay_1.setVisibility(View.VISIBLE);
                        tvPay_1.setTag(R.id.item_key_id, paymentModes.getCode());
                    } else if (i == 1 && paymentModes != null) {
                        tvPay_2.setText(paymentModes.getName());
                        tvPay_2.setVisibility(View.VISIBLE);
                        tvPay_2.setTag(R.id.item_key_id, paymentModes.getCode());
                    }
                }

                if (preProduct != null) {//预售商品
                    //获取商品价格配置
                    storePriceStr = getPreStorePrice();
                } else {
                    storePriceStr = getAllStoresPrice();
                }
                tvPursePrice.setText(getString(R.string.total_price, responseElement.getWallets()));
                changePaymentStatus();
                showPayWayViewChange();
                //是否显示优惠券
                boolean showCouponFlag = responseElement.isShowCouponFlag();
                showDiscountView(showCouponFlag);

                //计算价格
                reCountPrice();
                adapter.notifyDataSetChanged();
                updateCommitStatus();

                //配置是否显示时间选项
                updateDateView();

                deliveryType = getDeliveryType(groups.get(0).getDeliveryMode());
                updateColumnView();

//                // TODO: 2020/5/13 暂时这里处理新改的运费减免
//                double productExpressFeeReduce = responseElement.getProductExpressFeeReduce();
//                if (productExpressFeeReduce != 0) {
//                    tvReduceFeeTitle.setVisibility(View.VISIBLE);
//                    tvReduceFee.setVisibility(View.VISIBLE);
//                    tvReduceFee.setText("-" + productExpressFeeReduce + "元");
//                } else {
//                    tvReduceFeeTitle.setVisibility(View.GONE);
//                    tvReduceFee.setVisibility(View.GONE);
//                }
            }


        }
    };


    public void requestOrderGenerateBefore(Object carts, Address address) {
//        "cityId": "31",
//                "accountId": "90",
//                "destination": "上海市",
//                "longitude": "",
//                "latitude": "",
//                "receiverDetailsAddress": "",
        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_settle);

        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        if (address == null) {
            re.putParameter("destination", "");
            re.putParameter("longitude", "");
            re.putParameter("latitude", "");
            re.putParameter("receiverDetailsAddress", "");
        } else {
            re.putParameter("destination", address.getCityName());
            re.putParameter("longitude", address.getLng());
            re.putParameter("latitude", address.getLat());
            re.putParameter("receiverDistrictId", address.getDistrictId());
            re.putParameter("receiverDetailsAddress", address.getAddress());
            re.putParameter("receiverStreetId", address.getStreetId());
        }
        re.putParameter("specList", carts);
//        re.putParameter("specList", shoppingCarId);
        RequestTag rt = new RequestTag();
        rt.type = RequestTag.TYPE_CURRENT;
        rt.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_settle;
        request(re, rt, onRequestOrderGenerateBeforeListener);
    }

    OnRequestListener<Feed> onRequestFeedListener = new OnRequestListener<Feed>() {
        @Override
        public Feed jsonToObj(String s) {
/*            return new Gson().fromJson(s, new TypeToken<List<Feed>>() {
            }.getType());*/
            return new Gson().fromJson(s, Feed.class);

        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            toast("获取运费失败,请刷新");
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            toast("获取运费失败,请刷新");
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();

            isFeeError = true;
            tvBtn.setEnabled(false);
        }

        @Override
        public void onResponse(ResponseEntity<Feed> responseEntity, Object o) {

            isFeeError = false;
            hideProgressDialog();
            updateCommitStatus();
            Feed responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                ArrayList list = new ArrayList();
                list.add(responseElement);
                updateFeed(list);
            }
        }
    };


    public void requestFeed(FeedRequest feeds) {
        if (address == null || address.getAddressOnMap() == null || "".equals(address.getAddressOnMap())) {


            return;
        }
        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_calcFreight);
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("destination", feeds.getDestination());
        re.putParameter("longitude", feeds.getLongitude());
        re.putParameter("latitude", feeds.getLatitude());
        re.putParameter("receiverDetailsAddress", feeds.getReceiverDetailsAddress());

        re.putParameter("list", feeds.getList());
        //re.putParameter("accountId", getUser().getAccountId());


        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_calcFreight, onRequestFeedListener);
    }

    OnRequestListener<List<String>> onRequestFastMerTagListener = new OnRequestListener<List<String>>() {
        @Override
        public List<String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof CartGood) {

                    openMerMsg((CartGood) arg2, null);
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof CartGood) {

                    openMerMsg((CartGood) arg2, null);
                }
            }

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();


        }

        @Override
        public void onResponse(ResponseEntity<List<String>> responseEntity, Object o) {

            hideProgressDialog();
            List<String> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {

            }
            if (o != null && o instanceof RequestTag) {

                RequestTag tag = (RequestTag) o;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof CartGood) {

                    openMerMsg((CartGood) arg2, responseElement);
                }
            }
        }
    };

    RequestTag tag;

    public void requestFastMerTagList(CartGood cartGood) {

        if (cartGood == null) {
            return;
        }
        String nameId = cartGood.getProductNameId();
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByNameId);
        re.putParameter("nameId", nameId);

        tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByNameId;
        tag.arg2 = cartGood;
        tag.type = RequestTag.TYPE_CURRENT;
        request(re, tag, onRequestFastMerTagListener);
    }


    OrderFailDialog orderFailDialog;

    public void openOrderFailDialog(String s) {
        if (orderFailDialog == null) {
            orderFailDialog = new OrderFailDialog(this);
            orderFailDialog.setCancelable(false);
            orderFailDialog.setOnBackCartClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cart();
                }
            });
        }
        orderFailDialog.show(s);
    }

    OrderFailDialog orderDiscountDialog;

    public void openDiscountDialog(String content) {
        if (orderDiscountDialog == null) {
            orderDiscountDialog = new OrderFailDialog(this);
            orderDiscountDialog.setCancelable(false);
            orderDiscountDialog.setOnBackCartClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    orderDiscountDialog.dismiss();
                }
            });
        }
        orderDiscountDialog.show(content, "关闭");
    }


    public void cart() {

        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra("home_tab_index", 2);
        startActivity(intent);
        finish();
    }

    MerMsgDialog merMsgDialog;


    @Override
    protected void onDestroy() {

        RequestManager.getInstance().cancel("appOrder/createOrder");
        if (tag != null)
            RequestManager.getInstance().cancel(tag);
        super.onDestroy();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("CartOrder"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this);          //统计时长
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("CartOrder"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }


    @Override
    public void onBackPressed() {
        if (orderDiscountDialog != null && orderDiscountDialog.isShowing()) {
            orderDiscountDialog.dismiss();
        } else {
            super.onBackPressed();
        }
    }


    boolean refreshFlag;
    OnRequestListener<Map<String, Object>> onSaveMsgRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            toast(o + "");//arg + ",请点击重试"
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {
            hideProgressDialog();
            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {
                    msgSuccess();
                    refreshFlag = true;
                }
            }
        }
    };

    public void saveMsg(String msg, String goodsId) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg);
        re.putParameter("merMsg", msg);
        re.putParameter("shoppingCarId", goodsId);
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg, onSaveMsgRequestListener);
    }


    public void openMerMsg(CartGood cartGood, List<String> list) {
        if (merMsgDialog == null) {
            merMsgDialog = new MerMsgDialog(this);
            merMsgDialog.setOnMerMsgInputListener(new MerMsgDialog.OnMerMsgInputListener() {
                @Override
                public void onMerMsgInputListener(String msg, CartGood cartGood) {
                    if (!VerificationUtils.isValid(msg)) {
                        toast("不能输入特殊字符及表情符号");
                        return;
                    }
                    if (cartGood != null) {
                        CartOrderNewActivity.this.cartGood = cartGood;
                        CartOrderNewActivity.this.msg = msg;
                        if (cartGood.getSalesType().equals("2")) {
                            msgSuccess();
                        } else {
                            saveMsg(msg, cartGood.getShoppingCarId());
                        }
                    }
                    merMsgDialog.dismiss();
                }
            });
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        merMsgDialog.show(cartGood, list);
    }

    CartGood cartGood;
    String msg;

    void msgSuccess() {
        if (cartGood == null || msg == null || adapter == null)
            return;
        cartGood.setMerMsg(msg);
        mapMsg.put(cartGood.getShoppingCarId(), msg);
        adapter.notifyDataSetChanged();
    }

    private String getDeliveryType(String flag) {
        if (flag.equals("gatherDistribution")) {
            return "集单配送";

        } else if (flag.equals("selfDelivery")) {
            return "到店自提";

        } else if (flag.equals("merchantDelivery")) {
            return "商家配送";
        } else {
            return null;
        }
    }

    private void updateColumnView() {
        boolean showCouponFlag = cartList.isShowCouponFlag();
        double productExpressFeeReduce = cartList.getProductExpressFeeReduce();

        if (deliveryType.equals("集单配送")) {
            if (payType.equals("预先支付") && showCouponFlag) {
                //显示优惠券
                showDiscountView(true);
            } else {
                //不显示优惠券
                showDiscountView(false);
            }

            if (productExpressFeeReduce == 0) {
                //不显示运费减免
                tvReduceFeeTitle.setVisibility(View.GONE);
                tvReduceFee.setVisibility(View.GONE);
            } else {
                //显示运费减免
                tvReduceFeeTitle.setVisibility(View.VISIBLE);
                tvReduceFee.setVisibility(View.VISIBLE);
                tvReduceFee.setText("-" + productExpressFeeReduce + "元");
            }

        } else {
            //不显示优惠券
            showDiscountView(false);
            //不显示运费减免
            tvReduceFeeTitle.setVisibility(View.GONE);
            tvReduceFee.setVisibility(View.GONE);

        }
    }

}
